package com.uxsino.commons.utils;

import java.io.IOException;
import java.net.URL;
import java.util.function.Consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;

public class ClassPathResourceWalker {
    private static Logger logger = LoggerFactory.getLogger(ClassPathResourceWalker.class);

    String locationPattern;

    public ClassPathResourceWalker(String locationPattern) {
        this.locationPattern = locationPattern;
    }

    public void forEach(Consumer<URL> action) throws IOException {
        ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver();
        Resource[] rs = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources(locationPattern);
        for (Resource r : rs) {
            try {
                action.accept(r.getURL());
            } catch (IOException e) {
                logger.error("error in file url:{}", e);
            }
        }
    }

}
